﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;

namespace API.Core.MediaTypeFormatter
{

    public class MultiFormDataMediaTypeFormatter : System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter
    {
        public MultiFormDataMediaTypeFormatter() : base()
        {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
        }

        public override bool CanReadType(Type type)
        {
            return true;
        }

        public override bool CanWriteType(Type type)
        {
            return false;
        }

        public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, System.Net.Http.Formatting.IFormatterLogger formatterLogger)
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(CommerceML.Version205.КоммерческаяИнформация));

            if (!content.IsMimeMultipartContent())
            {
                throw new System.Web.Http.HttpResponseException(System.Net.HttpStatusCode.UnsupportedMediaType);
            }

            var Parts = await content.ReadAsMultipartAsync();
            var FileContent = Parts.Contents.First();

            using (var stream = await FileContent.ReadAsStreamAsync())
            {
                var commerceML = serializer.Deserialize(stream);
                var data = new Core.CommerceMLConverter().Convert(commerceML as CommerceML.Version205.КоммерческаяИнформация);

                return data;
            }

        }
    }
}